require.config({
    paths: {
        'editable': '../libs/bootstrap-table/dist/extensions/editable/bootstrap-table-editable.min',
        'x-editable': '../addons/workteam/js/bootstrap-editable.min',
    },
    shim: {
        'editable': {
            deps: ['x-editable', 'bootstrap-table']
        },
        "x-editable": {
            // deps: ["css!../addons/workteam/css/bootstrap-editable.css"],
        }
    }
});

define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'editable'], function ($, undefined, Backend, Table, Form,Editable) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'workteam/task/index' + location.search,
                    add_url: 'workteam/task/add',
                    edit_url: 'workteam/task/edit',
                    del_url: 'workteam/task/del',
                    multi_url: 'workteam/task/multi',
                    start_url: 'workteam/task/start',//开始任务和修改进度都是这里
                    table: 'workteam_task',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: '',
	            pageSize: 50,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id') , sortable: true},
                        {
                            field: 'scene_id',
                            title: __('场景'),
                            visible: false,
                            formatter: function (v, r) {
                                return Config.scene_list[v];
                            }, searchList: Config.scene_list
                        },
                        {field: 'project.name', title: __('项目'),operate:false,align: 'left'},
                        {field: 'project_id', title: __('项目'),addclass: 'selectpage',visible:false,
                            extend: "data-source='workteam/project/index' data-field='name'"},

                        {field: 'name', title: __('任务'),align: 'left'
                            ,customField: 'level'
                            ,formatter: function (value, row, index) {
                                //判断是否逾期
                                var newtime = Math.round(new Date().getTime()/1000).toString();
                                if (newtime>row.end_time&&row.status!=2)
                                    value='<span class="label label-danger">逾</span>'+value;
                                return value +
                                    Controller.api.level(row['level'], row, index,this);
                            }},
                        {field: 'admin.nickname', title: __('负责人'),operate:false},
                        {field: 'admin_id', title: __('负责人'),addclass: 'selectpage',visible:false,
                            extend: "data-source='workteam/common/selectpage/model/admin/type/all' data-field='nickname'"},
                        {field: 'plan_hours', title: __('计划工时'), operate: 'BETWEEN', sortable: true},
                        {field: 'get_hours', title: __('可得工时'), operate: 'BETWEEN', sortable: true,},
                        {
                            field: 'progress',
                            title: __('进度'),
                            editable: true,
                            operate: false,
                            formatter: function (value, row, index) {
                                var str =value+'%';
                                return str;
                            }
                        },
                        {field: 'status', title: __('Status'), searchList: Config.statusList, formatter: Table.api.formatter.status},
                        {field: 'level', title: __('优先级'), searchList: Config.levelList,visible:false, formatter: Table.api.formatter.status},
                        {field: 'start_time', title: __('开始日期'), operate: 'RANGE', addclass: 'datetimerange', formatter: Controller.api.formatter.datetime,sortable: true},
                        {field: 'end_time', title: __('截止日期'), operate: 'RANGE', addclass: 'datetimerange', formatter: Controller.api.formatter.datetime,sortable: true},
                        {field: 'create_time', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Controller.api.formatter.datetime,sortable: true},
                        {field: 'update_time', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Controller.api.formatter.datetime,sortable: true},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'start',
                                    text: '',
                                    title: __('开始任务'),
                                    icon: 'fa fa-play-circle-o',
                                    confirm: __("确认开始任务"),
                                    classname: 'btn btn-xs btn-info btn-ajax',
                                    url: 'workteam/task/start',
                                    hidden:function (row) {
                                        if (row.status!=0) return true;
                                    },
                                    success:function () {
                                        $(".btn-refresh").trigger('click');
                                    }
                                },
                                {
                                    name: 'complete',
                                    text: '',
                                    title: __('完成任务'),
                                    icon: 'fa fa-check-circle',
                                    // classname: 'btn btn-xs btn-info btn-ajax',
                                    // confirm: __("确认完成任务？完成之后不能再操作"),
	                                classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'workteam/task/complete',
                                    hidden:function (row) {
                                        if (row.status!=1) return true;
                                    },
                                    success:function () {
                                        $(".btn-refresh").trigger('click');
                                    }
                                },
                                {
                                    name: 'ucomplete',
                                    text: '',
                                    title: __('反完成任务'),
                                    icon: 'fa fa-mail-reply',
                                    classname: 'btn btn-xs btn-info btn-ajax',
                                    confirm: __("是否反完成任务？将任务撤回进行中状态。"),
                                    url: 'workteam/task/ucomplete',
                                    hidden:function (row) {
                                        if (row.status!=2) return true;
                                        if ($.inArray(row.project.status,[1,0])==-1) return true;
                                    },
                                    success:function () {
                                        $(".btn-refresh").trigger('click');
                                    }
                                },
                                {
                                    name: 'addchild',
                                    text: '',
                                    title: __('添加子任务'),
                                    icon: 'fa fa-plus',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: 'workteam/task/addchild',
                                    hidden:function (row) {
                                        if ($.inArray(row.status,[1,0])==-1) return true;
                                    },
                                },
                                {
                                    name: 'detail',
                                    text: __('详情'),
                                    title: __('任务详情'),
                                    icon: '',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    url: 'workteam/task/detail',
                                },
                            ]}
                    ]
                ],
                onEditableSave:function (field, row, oldValue, $el) {

                    var data = {};
                    data[field] = row[field];
                    Fast.api.ajax({
                        url: $.fn.bootstrapTable.defaults.extend.start_url + "/ids/" + row[this.pk],
                        data: data
                    },function () {
                        $(".btn-refresh").trigger("click");
                    });
                },
                //启用固定列
                fixedColumns: true,
                //固定右侧列数
                fixedRightNumber: 1,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
			Controller.api.cycle();
        },
        addlog:function(){
            Controller.api.bindevent();
            //通知
            $("#c-notice").on("click",function () {
                $(".admin-ids-div").toggle();
            });
        },
        complete:function(){
            Controller.api.bindevent();
            //通知
            $("#c-notice").on("click",function () {
                $(".admin-ids-div").toggle();
            });
        },
        detail: function () {
            Controller.api.bindevent();
            // 初始化表格参数配置
            Table.api.init();

            var tablelog = $("#tablelog");

            // 初始化表格
            tablelog.bootstrapTable({
                url: 'workteam/log/index/task_id/'+pid,
	            extend: {
                    add_url: '',
                    edit_url: '',
                    del_url: 'workteam/log/del/task_id/'+pid,
                    multi_url: 'workteam/log/multi/task_id/'+pid,
                },
                toolbar: '#toolbar1',
                queryParams: function (params) { // 请求服务器数据时发送的参数，可以在这里添加额外的查询参数，返回false则终止请求
                    var activeobj= $('#tab-log .active a[data-toggle="tab"]');
                    params.filter= JSON.stringify($(activeobj).data('filter'));
                    params.op= JSON.stringify(activeobj.data('op'));
                    return params
                },
                columns: [
                    [
                        {field: 'id', title: 'ID', operate: false},
                        {field: 'type', title: __('类型'), operate: false,formatter:function (val,row) {
                                return row.type_text;
                            } },
                        {field: 'create_type', title: __('录入方式'),custom:{1:'danger',0:'info'},formatter:Table.api.formatter.flag,searchList:Config.createTypeList},
                        {field: 'username', title: __('Username'), formatter: Table.api.formatter.search},
                        {field: 'title', title: __('Title'), operate: 'LIKE %...%', placeholder: '模糊搜索'},
                        {field: 'content_text', title: __('内容'), operate: false,formatter:function (val) {
                                return '<div class="logcontent" data-toggle="tooltip" data-title="'+val+'">'+val+'</div>';
                            }},
                        {field: 'create_time', title: __('Create time'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
                        {field: 'operate', title: __('Operate'), table: tablelog,
                            events: Table.api.events.operate,
                            buttons: [{
                                name: 'detail',
                                text: __('Detail'),
                                icon: 'fa fa-list',
                                classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                url: 'workteam/log/detail',
                            }],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(tablelog);

			// 绑定TAB事件
            $('#tab-log a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                tablelog.bootstrapTable('refresh', {pageNumber: 1});
                return false;
            });


            Table.api.init();

            var childtask = $("#childtask");

            // 初始化表格

            childtask.bootstrapTable({
                url: 'workteam/task/childList/ids/' + pid,
                toolbar: '#toolbar2',
	            extend: {
                    add_url: '',
                    edit_url: '',
                    del_url: 'workteam/task/del',
                    multi_url: 'workteam/task/multi',
                },
                columns: [
                    [
                        {field: 'name', title: __('任务名称')},
                        {field: 'admin.nickname', title: __('负责人'),operate:false},
                        {field: 'admin_id', title: __('负责人'),addclass: 'selectpage',visible:false,
                            extend: "data-source='workteam/common/selectpage/model/admin/type/all' data-field='nickname'"},
                        {field: 'plan_hours', title: __('计划工时'), operate: 'BETWEEN', sortable: true},
                        {field: 'get_hours', title: __('可得工时'), operate: 'BETWEEN', sortable: true},

                        {field: 'status', title: __('Status'), searchList: Config.statusList, formatter: Table.api.formatter.status},
                        {field: 'start_time', title: __('开始日期'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'end_time', title: __('截止日期'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'create_time', title: __('Createtime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'update_time', title: __('Updatetime'), operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime,sortable: true},
                        {field: 'operate', title: __('Operate'), table: childtask, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'start',
                                    text: '',
                                    title: __('开始任务'),
                                    icon: 'fa fa-play-circle-o',
                                    confirm: __("确认开始任务"),
                                    classname: 'btn btn-xs btn-info btn-ajax',
                                    url: 'workteam/task/start',
                                    hidden:function (row) {
                                        if (row.status!=0) return true;
                                    },
                                    success:function () {
                                        $(".btn-refresh").trigger('click');
                                    }
                                },
                                {
                                    name: 'complete',
                                    text: '',
                                    title: __('完成任务'),
                                    icon: 'fa fa-check-circle',
                                    // classname: 'btn btn-xs btn-info btn-ajax',
                                    // confirm: __("确认完成任务？完成之后不能再操作"),
	                                classname: 'btn btn-xs btn-success btn-dialog',
                                    url: 'workteam/task/complete',
                                    hidden:function (row) {
                                        if (row.status!=1) return true;
                                    },
                                    success:function () {
                                        $(".btn-refresh").trigger('click');
                                    }
                                },
                                {
                                    name: 'addchild',
                                    text: '',
                                    title: __('添加子任务'),
                                    icon: 'fa fa-plus',
                                    classname: 'btn btn-xs btn-danger btn-dialog',
                                    url: 'workteam/task/addchild',
                                },
                                {
                                    name: 'detail',
                                    text: __('详情'),
                                    title: __('任务详情'),
                                    icon: '',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    url: 'workteam/task/detail',
                                },
                            ]}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(childtask);


            Table.api.init();

            var loglist = $("#loglist");

            // 初始化表格

            loglist.bootstrapTable({
                url: 'service/log/index/task_id/' + pid,
                toolbar: '#toolbar3',
	            extend: {
                    add_url: 'service/log/add',
                    edit_url: 'service/log/edit',
                    del_url: 'service/log/del',
                },
                columns: [
                    [
                        {field: 'task.name', title: __('任务名称'), table: loglist, class: 'autocontent',
	                        formatter: function (value, row, index) {
								if (!value) return '-';
								return value;
							}
						},
                        {field: 'service_client_text', title: __('服务对象'), table: loglist, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'service_time', title: __('服务时间'), addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'content_text', title: __('可公开内容'), table: loglist, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'secret_text', title: __('隐私内容'), table: loglist, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'admin.nickname', title: __('创建人')},
                        {field: 'operate', title: __('Operate'), table: loglist, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(loglist);


        },
        addchild: function () {
            Form.api.bindevent($("form[role=form]"), function(data, ret){
				// 刷新日历
				if(typeof parent.calendar != 'undefined') parent.calendar.fullCalendar('refetchEvents');
                //绑定时间
                Fast.api.close(data);//在这里关闭当前弹窗
            });
            $("#c-pid").data("eSelect", function(data){
                Controller.api.taskajax(data.id);
            });
            $(document).on("change", "#c-status", function(data,res){
                if ($(this).val()>=2){
                    $(".complete_time").show();
                }else{
                    $(".complete_time").hide();
                }
            });
			Controller.api.cycle();
        },
        edit: function () {
            Controller.api.bindevent();
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'workteam/task/fileslist/task_id/'+task_id,
                    add_url: 'workteam/task/filesadd/task_id/'+task_id ,
                    edit_url: '',
                    del_url: 'workteam/task/filesdel/task_id/'+task_id ,
                    multi_url: '',
                    table: ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [
                        {field: 'id', title: __('Id')},
                        {field: 'admin.nickname', title: __('上传人'), operate: false},
                        {field: 'admin_id', title: __('上传人'), visible: false, addClass: "selectpage", extend: "data-source='auth/admin/index' data-field='nickname'"},
                        {field: 'preview', title: __('预览'), formatter: Controller.api.formatter.thumb, operate: false},
                        {field: 'filename', title: __('文件名称'), operate: false},
                        {field: 'url', title: __('文件地址'), formatter: Controller.api.formatter.url, visible: false},
                        {
                            field: 'create_time',
                            title: __('Createtime'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            //上传附件
            $("#c-third").on("change",function () {
                var url=$(this).val();
                if (url){
                    $(this).val("");
                    Fast.api.ajax({
                        url: $.fn.bootstrapTable.defaults.extend.add_url,
                        data: {url:url}
                    },function (data) {
                        table.bootstrapTable('refresh', {pageNumber: 1});
                    });
                }
            });
        },

        fileslist:function(){
            Controller.api.bindevent();
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'workteam/task/fileslist/task_id/'+task_id,
                    add_url: 'workteam/task/filesadd/task_id/'+task_id,
                    edit_url: '',
                    del_url: 'workteam/task/filesdel/task_id/'+task_id,
                    multi_url: '',
                    table: ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                sortName: 'id',
                columns: [
                    [
                        {field: 'id', title: __('Id')},
                        {field: 'admin.nickname', title: __('上传人'), operate: false},
                        {field: 'admin_id', title: __('上传人'), visible: false, addClass: "selectpage", extend: "data-source='auth/admin/index' data-field='nickname'"},
                        {field: 'preview', title: __('预览'), formatter: Controller.api.formatter.thumb, operate: false},
                        {field: 'filename', title: __('文件名称'), operate: false},
                        {field: 'url', title: __('文件地址'), formatter: Controller.api.formatter.url, visible: false},
                        {
                            field: 'create_time',
                            title: __('Createtime'),
                            formatter: Table.api.formatter.datetime,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            sortable: true
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ],
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            //上传附件
            $("#c-third").on("change",function () {
                var url=$(this).val();
                if (url){
                    $(this).val("");
                    Fast.api.ajax({
                        url: $.fn.bootstrapTable.defaults.extend.add_url,
                        data: {url:url}
                    },function (data) {
                        table.bootstrapTable('refresh', {pageNumber: 1});
                    });
                }
            });
        },

        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"), function(data, ret){
					// 刷新日历
					if(typeof parent.calendar != 'undefined' && parent.calendar != null) parent.calendar.fullCalendar('refetchEvents');
                    //绑定时间
                    Fast.api.close(data);//在这里关闭当前弹窗
                });
                var project_id=$("#c-project_id").val();
                if (project_id){
                    Controller.api.projectajax(project_id);
                }
                $("#c-project_id").data("eSelect", function(data){
                   Controller.api.projectajax(data.id);
                });
                $(document).on("change", "#c-status", function(data,res){
                    if ($(this).val()>=2){
                        $(".complete_time").show();
                    }else{
                        $(".complete_time").hide();
                    }
                });
            },
	        cycle: function(){
				$('[name="cycle"]').on('click', function(){
					const cycle_type = $(this).val();
					if(cycle_type == 0){
						$('.cycle').hide();
					}else if(cycle_type == 1 || cycle_type == 4){
						$('.cycle').hide();
						$('#cycle-day').show();
					}else if(cycle_type == 2){
						$('.cycle').hide();
						$('#cycle-week').show();
					}else if(cycle_type == 3){
						$('.cycle').hide();
						$('#cycle-month').show();
					}
				})
	        },
            projectajax:function (project_id) {
                //后续操作
                Fast.api.ajax({
                        url:'workteam/project/info/ids/'+project_id,
                    }
                    , function (res) {
                        $('.text-end_time').html(__("最迟")+(new Date(parseInt(res.end_time) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ')));
                        var plan_hours=res.plan_hours-res.task_hours
                        var plan_hours_str=plan_hours>=0?__("剩余")+plan_hours+__("工时"):__("已超出")+Math.abs(plan_hours)+__("工时");
                        $('.text-plan_hours').html(plan_hours_str)
                        return false;
                    }, function () {

                    });
            },
            taskajax:function (id) {
                //后续操作
                Fast.api.ajax({
                        url:'workteam/task/info/ids/'+id,
                    }
                    , function (res) {
                        $('.text-end_time').html(__("最迟")+(new Date(parseInt(res.end_time) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ')));
                        var plan_hours=res.plan_hours-res.task_hours
                        var plan_hours_str=plan_hours>=0?__("剩余")+plan_hours+__("工时"):__("已超出")+Math.abs(plan_hours)+__("工时");
                        $('.text-plan_hours').html(plan_hours_str)
                        return false;
                    }, function () {

                    });
            },

            level: function (value, row, index,obj) {
                if (value==1) return '';
                var colorArr = ["primary", "success", "default", "info", "warning", "danger", "red", "yellow", "aqua", "blue", "navy", "teal", "olive", "lime", "fuchsia", "purple", "maroon"];

                var field = obj.field;
                if (typeof obj.customField !== 'undefined' && typeof row[obj.customField] !== 'undefined') {
                    field = obj.customField;
                }
                var color = index > -1 && typeof colorArr[value] !== 'undefined' ? colorArr[value] : 'primary';
                var icon='',display=Config.levelList[value];
                var html = '<span class="label label-' + color + '">' + display + '</span>';
                if (obj.operate != false) {
                    html = '<a href="javascript:;" class="searchit" data-toggle="tooltip" title="' + __('Click to search %s', display) + '" data-field="' + field + '" data-value="' + value + '">' + html + '</a>';
                }
                return html;
            },

            formatter: {
                thumb: function (value, row, index) {
                    var reg=/.*(\.png|\.jpg|\.jpeg|\.gif)$/;
                    if (reg.test(row.fullurl)) {
                        return '<a href="' + row.fullurl + '" target="_blank"><img src="' + row.fullurl  + '" alt="" style="max-height:90px;max-width:120px"></a>';
                    } else {
                        return '<a href="' + row.fullurl + '" target="_blank"><img src="' + Fast.api.fixurl("ajax/icon") + "?suffix=" + row.imagetype + '" alt="" style="max-height:90px;max-width:120px"></a>';
                    }
                },
                url: function (value, row, index) {
                    return '<a href="' + row.fullurl + '" target="_blank" class="label bg-green">' + row.url + '</a>';
                },
                filename: function (value, row, index) {
                    return '<div style="width:180px;margin:0 auto;text-align:center;overflow:hidden;white-space: nowrap;text-overflow: ellipsis;">' + Table.api.formatter.search.call(this, value, row, index) + '</div>';
                },
                datetime: function (value, row, index) {
                    var datetimeFormat = typeof this.datetimeFormat === 'undefined' ? 'YYYY/MM/DD HH:mm' : this.datetimeFormat;
                    if (isNaN(value)) {
                        return value ? Moment(value).format(datetimeFormat) : __('None');
                    } else {
                        return value ? Moment(parseInt(value) * 1000).format(datetimeFormat) : __('None');
                    }
                },
            }
        }
    };
    return Controller;
});